"use client"

import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Sparkles, Plus, Trash2, LogOut, Loader2 } from "lucide-react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { fetchWithJwtToken, JWT_TOKEN_KEY } from "@/lib/utils"

interface User {
  id: number;
  username: string;
}

interface GenerationStyle {
  id: string
  name: string
  description: string
}

interface Project {
  id: string
  title: string
}

interface GenerationHistory {
  id: string
  prompt: string
  coverImageUrl: string
  title: string
  tags: string[]
  content: string
}

export function GeneratorClient({ user }: { user: User | null }) {
  const router = useRouter()

  const [styles, setStyles] = useState<GenerationStyle[]>([])
  const [projects, setProjects] = useState<Project[]>([])
  const [selectedProject, setSelectedProject] = useState<Project | null>(null)
  const [history, setHistory] = useState<GenerationHistory[]>([])
  const [selectedHistory, setSelectedHistory] = useState<GenerationHistory | null>(null)

  const [selectedStyle, setSelectedStyle] = useState<string>("")
  const [prompt, setPrompt] = useState("")
  const [isGenerating, setIsGenerating] = useState(false)
  const [generatedContent, setGeneratedContent] = useState<GenerationHistory | null>(null)

  const [trialCount, setTrialCount] = useState(0)
  const TRIAL_LIMIT = 5

  const [showCreateDialog, setShowCreateDialog] = useState(false)
  const [newTaskTitle, setNewTaskTitle] = useState("")

  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
  const [taskToDelete, setTaskToDelete] = useState<Project | null>(null)

  const [showDeleteHistoryDialog, setShowDeleteHistoryDialog] = useState(false)
  const [historyToDelete, setHistoryToDelete] = useState<GenerationHistory | null>(null)

  const promptExamples = [
    {
      title: "美食探店",
      prompt: "分享一家性价比超高的日料店，环境优雅，适合约会，招牌三文鱼刺身新鲜肥美",
      styleId: "清新文艺", // 生活方式风格
    },
    {
      title: "旅游攻略",
      prompt: "三天两夜成都旅游攻略，包含必打卡景点、特色美食推荐和住宿建议",
      styleId: "干货分享", // 专业干货风格
    },
    {
      title: "穿搭分享",
      prompt: "秋季通勤穿搭指南，简约大方又显气质，适合上班族的日常搭配",
      styleId: "清新文艺", // 时尚潮流风格
    },
    {
      title: "护肤心得",
      prompt: "敏感肌护肤品推荐，温和不刺激，使用一个月后皮肤状态明显改善",
      styleId: "干货分享", // 生活方式风格
    },
    {
      title: "生活好物",
      prompt: "提升幸福感的家居好物分享，实用又美观，让生活更有仪式感",
      styleId: "情感共鸣", // 生活方式风格
    },
    {
      title: "健身打卡",
      prompt: "新手居家健身计划，每天30分钟，坚持一个月瘦了10斤",
      styleId: "情感共鸣", // 励志鸡汤风格
    },
  ]

  useEffect(() => {
    loadStyles()
    if (user) {
      loadProjects()
    } else {
      loadTrialCount()
    }
  }, [user])

  useEffect(() => {
    if (styles.length > 0 && !selectedStyle) {
      setSelectedStyle(styles[0].id)
    }
  }, [styles])

  useEffect(() => {
    if (selectedProject) {
      loadHistory(selectedProject.id)
    }
  }, [selectedProject])

  const loadStyles = async () => {
    const data = await fetchWithJwtToken('/api/styles')
    if (data) setStyles(data)
  }

  const loadProjects = async () => {
    if (!user) return
    const data = await fetchWithJwtToken(`/api/tasks?page=1&size=100`)
    if (data) {
      setProjects(data)
      if (!selectedProject || !data.find((p: Project) => p.id === selectedProject.id)) {
        setSelectedProject(data[0] || null)
      }
    }
  }

  const processHistoryItem = (item: GenerationHistory) => {
    if (!item.coverImageUrl) {
      item.coverImageUrl = "/placeholder.svg"
    }
    if (!item.coverImageUrl.startsWith("data:") && !item.coverImageUrl.startsWith("http")) {
      item.coverImageUrl = `data:image/png;base64,${item.coverImageUrl}`
    }
    if (!item.tags || !Array.isArray(item.tags)) {
      item.tags = (item.tags as string || '').split(/[,，\s]/).map((t: string) => t.trim().replace(/^#/, '')).filter((t: string) => t)
    }
    return item
  }

  const loadHistory = async (projectId: string) => {
    if (!user) return
    const data = await fetchWithJwtToken(`/api/tasks/${projectId}`)
    const list = data?.generateHistoryList || []
    if (list && Array.isArray(list) && list.length > 0) {
      list.forEach(processHistoryItem)
      setHistory(list)
    }
  }

  const loadTrialCount = () => {
    const count = Number.parseInt(localStorage.getItem("trialCount") || "0")
    setTrialCount(count)
  }

  const createProject = async () => {
    if (!user) return
    setNewTaskTitle("")
    setShowCreateDialog(true)
  }

  const handleCreateTask = async () => {
    if (!newTaskTitle.trim()) return
    
    try {
      const response = await fetchWithJwtToken('/api/tasks/create', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `title=${encodeURIComponent(newTaskTitle)}`
      })
      
      if (response) {
        setShowCreateDialog(false)
        setNewTaskTitle("")
        loadProjects()
      }
    } catch (error) {
      console.error('创建任务失败:', error)
    }
  }

  const deleteProject = async (projectId: string) => {
    if (!user) return
    const project = projects.find(p => p.id === projectId)
    if (project) {
      setTaskToDelete(project)
      setShowDeleteDialog(true)
    }
  }

  const handleDeleteTask = async () => {
    if (!taskToDelete) return
    
    try {
      await fetchWithJwtToken(`/api/tasks/${taskToDelete.id}`, {
        method: 'DELETE'
      })
      
      // 删除成功，关闭对话框并刷新项目列表
      setShowDeleteDialog(false)
      setTaskToDelete(null)
      loadProjects()
    } catch (error) {
      console.error('删除任务失败:', error)
    }
  }

  const deleteHistory = (historyId: string) => {
    if (!user) return
    const item = history.find(h => h.id === historyId) || null
    setHistoryToDelete(item)
    setShowDeleteHistoryDialog(true)
  }

  const handleDeleteHistory = async () => {
    if (!historyToDelete) return
    try {
      await fetchWithJwtToken(`/api/tasks/GenerateHistory/${historyToDelete.id}`, {
        method: 'DELETE'
      })
      setShowDeleteHistoryDialog(false)
      const deletedId = historyToDelete.id
      setHistoryToDelete(null)
      if (selectedProject) {
        await loadHistory(selectedProject.id)
      }
      if (selectedHistory?.id === deletedId) {
        setSelectedHistory(null)
      }
    } catch (error) {
      console.error('删除历史失败:', error)
    }
  }

  const handleGenerate = async () => {
    if (!selectedStyle || !prompt) return

    // Check trial limit for non-logged-in users
    if (!user) {
      if (trialCount >= TRIAL_LIMIT) {
        alert("试用次数已用完，请注册登录以继续使用")
        router.push("/auth/sign-up")
        return
      }
    }

    setIsGenerating(true)

    try {
      const mockGeneration = {
        id: crypto.randomUUID(),
        prompt,
        coverImageUrl: `/placeholder.svg?height=400&width=400&query=${encodeURIComponent(prompt)}`,
        title: `${prompt.slice(0, 20)}的爆款标题 | 必看攻略`,
        tags: ["热门", "推荐", "干货分享"],
        content: `这是关于"${prompt}"的精彩内容！\n\n✨ 亮点一：超级实用的技巧分享\n✨ 亮点二：详细的步骤说明\n✨ 亮点三：真实的使用体验\n\n姐妹们，这个真的太好用了！强烈推荐给大家～`,
      }

      await fetchWithJwtToken('/api/generate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
          style: styles.find(item => item.id === selectedStyle)?.name || "",
          prompt,
          taskId: selectedProject?.id || '',
        })
      }).then(data => {
        if (!data || !data.title) {
          throw new Error("生成失败")
        }
        setGeneratedContent(processHistoryItem(data))
      }).catch(() => {
        setGeneratedContent(mockGeneration)
      })

      // Save to database if user is logged in
      if (user && selectedProject) {
        loadHistory(selectedProject.id)
      } else {
        // Update trial count
        const newCount = trialCount + 1
        setTrialCount(newCount)
        localStorage.setItem("trialCount", newCount.toString())
      }
    } catch (error) {
      console.error("Generation error:", error)
      alert("生成失败，请重试")
    } finally {
      setIsGenerating(false)
    }
  }

  const handleLogout = async () => {
    localStorage.removeItem(JWT_TOKEN_KEY)
    router.push("/")
    router.refresh()
  }

  return (
    <div className="flex h-screen flex-col">
      {/* Header */}
      <header className="flex h-16 items-center justify-between border-b bg-background px-6">
        <Link href="/" className="flex items-center gap-2">
          <Sparkles className="h-6 w-6 text-primary" />
          <span className="text-xl font-bold">小红书 AI 生成器</span>
        </Link>
        <div className="flex items-center gap-4">
          {user ? (
            <>
              <div className="flex items-center gap-2 text-sm text-muted-foreground">
                <Sparkles className="h-4 w-4" />
                {user.username}
              </div>
              <Button variant="ghost" size="sm" onClick={handleLogout}>
                <LogOut className="mr-2 h-4 w-4" />
                退出
              </Button>
            </>
          ) : (
            <>
              <div className="text-sm text-muted-foreground">
                试用次数: {trialCount}/{TRIAL_LIMIT}
              </div>
              <Link href="/auth/login">
                <Button variant="ghost" size="sm">
                  登录
                </Button>
              </Link>
              <Link href="/auth/sign-up">
                <Button size="sm">注册</Button>
              </Link>
            </>
          )}
        </div>
      </header>

      {/* Main Content */}
      <div className="flex flex-1 overflow-hidden">
        {/* Left Sidebar - Projects */}
        {user && (
          <div className="w-48 border-r bg-muted/30">
            <div className="flex h-12 items-center justify-between border-b px-4">
              <h2 className="font-semibold">我的项目</h2>
              <Button size="sm" variant="ghost" onClick={createProject}>
                <Plus className="h-4 w-4" />
              </Button>
            </div>
            <ScrollArea className="h-[calc(100vh-7rem)]">
              <div className="space-y-1 p-2">
                {projects.map((project) => (
                  <div
                    key={project.id}
                    className={`group flex items-center justify-between rounded-lg px-3 py-2 text-sm cursor-pointer hover:bg-accent ${
                      selectedProject?.id === project.id ? "bg-accent" : ""
                    }`}
                    onClick={() => setSelectedProject(project)}
                  >
                    <span className="truncate">{project.title}</span>
                    <Button
                      size="sm"
                      variant="ghost"
                      className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100 hover:cursor-pointer"
                      onClick={(e) => {
                        e.stopPropagation()
                        deleteProject(project.id)
                      }}
                    >
                      <Trash2 className="h-3 w-3" />
                    </Button>
                  </div>
                ))}
              </div>
            </ScrollArea>
          </div>
        )}

        {/* Middle Sidebar - History */}
        {user && selectedProject && history.length > 0 && (
          <div className="w-72 border-r bg-background">
            <div className="flex h-12 items-center border-b px-4">
              <h2 className="font-semibold">生成历史</h2>
            </div>
            <ScrollArea className="h-[calc(100vh-7rem)]">
              <div className="space-y-2 p-2">
                {history.map((item) => (
                  <Card
                    key={item.id}
                    className={`group cursor-pointer p-3 hover:border-primary ${
                      selectedHistory?.id === item.id ? "border-primary" : ""
                    }`}
                    onClick={() => setSelectedHistory(item)}
                  >
                    <div className="flex gap-3">
                      <img
                        src={item.coverImageUrl || "/placeholder.svg"}
                        alt=""
                        className="h-16 w-16 rounded object-cover"
                      />
                      <div className="flex-1 space-y-1 overflow-hidden">
                        <h3 className="truncate text-sm font-medium">{item.title}</h3>
                        <p className="truncate text-xs text-muted-foreground">{item.prompt}</p>
                        <div className="flex items-center justify-between">
                          <div className="flex flex-wrap gap-1">
                            {item.tags.slice(0, 2).map((tag, i) => (
                              <span key={i} className="rounded bg-muted px-1.5 py-0.5 text-xs">
                                {tag}
                              </span>
                            ))}
                          </div>
                          <Button
                            size="sm"
                            variant="ghost"
                            className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100"
                            onClick={(e) => {
                              e.stopPropagation()
                              deleteHistory(item.id)
                            }}
                          >
                            <Trash2 className="h-3 w-3" />
                          </Button>
                        </div>
                      </div>
                    </div>
                  </Card>
                ))}
              </div>
            </ScrollArea>
          </div>
        )}

        {/* Main Area - Generator */}
        <div className="flex-1 overflow-auto">
          <div className="mx-auto max-w-4xl p-6">
            {selectedHistory ? (
              // Display selected history
              <div className="space-y-6">
                <Button variant="ghost" onClick={() => setSelectedHistory(null)}>
                  ← 返回生成
                </Button>
                <Card className="overflow-hidden">
                  <img
                    src={selectedHistory.coverImageUrl || "/placeholder.svg"}
                    alt=""
                    className="h-64 w-full object-cover"
                  />
                  <div className="p-6 space-y-4">
                    <h1 className="text-2xl font-bold">{selectedHistory.title}</h1>
                    <div className="flex flex-wrap gap-2">
                      {selectedHistory.tags.map((tag, i) => (
                        <span
                          key={i}
                          className="rounded-full bg-pink-100 px-3 py-1 text-sm text-pink-700 dark:bg-pink-900/20 dark:text-pink-400"
                        >
                          #{tag}
                        </span>
                      ))}
                    </div>
                    <div className="whitespace-pre-wrap text-muted-foreground">{selectedHistory.content}</div>
                  </div>
                </Card>
                <div className="flex justify-center">
                  <Button
                    onClick={() => setSelectedHistory(null)}
                    className="h-12 text-base"
                    style={{ width: "min(80%, 600px)" }}
                  >
                    继续生成
                  </Button>
                </div>
              </div>
            ) : generatedContent ? (
              // Display generated content
              <div className="space-y-6">
                <div className="flex items-center justify-between">
                  <h2 className="text-2xl font-bold">生成结果</h2>
                  <Button onClick={() => setGeneratedContent(null)}>继续生成</Button>
                </div>
                <Card className="overflow-hidden">
                  <img
                    src={generatedContent.coverImageUrl || "/placeholder.svg"}
                    alt=""
                    className="h-64 w-full object-cover"
                  />
                  <div className="p-6 space-y-4">
                    <h1 className="text-2xl font-bold">{generatedContent.title}</h1>
                    <div className="flex flex-wrap gap-2">
                      {generatedContent.tags.map((tag, i) => (
                        <span
                          key={i}
                          className="rounded-full bg-pink-100 px-3 py-1 text-sm text-pink-700 dark:bg-pink-900/20 dark:text-pink-400"
                        >
                          #{tag}
                        </span>
                      ))}
                    </div>
                    <div className="whitespace-pre-wrap text-muted-foreground">{generatedContent.content}</div>
                  </div>
                </Card>
              </div>
            ) : (
              // Generator form
              <div className="space-y-6">
                <div>
                  <h2 className="mb-2 text-2xl font-bold">创建爆款内容</h2>
                  <p className="text-muted-foreground">选择生成风格，输入内容提示，让 AI 为你创作</p>
                </div>

                {!user && (
                  <Card className="border-orange-200 bg-orange-50 p-4 dark:border-orange-900 dark:bg-orange-900/10">
                    <p className="text-sm text-orange-900 dark:text-orange-200">
                      您正在使用试用模式，剩余 {TRIAL_LIMIT - trialCount} 次生成机会。
                      <Link href="/auth/sign-up" className="ml-2 underline">
                        注册账号
                      </Link>
                      享受无限次数。
                    </p>
                  </Card>
                )}

                {user && !selectedProject && (
                  <Card className="border-blue-200 bg-blue-50 p-4 dark:border-blue-900 dark:bg-blue-900/10">
                    <p className="text-sm text-blue-900 dark:text-blue-200">
                      请先创建一个项目来保存您的生成历史。
                      <Button variant="link" className="ml-2 h-auto p-0" onClick={createProject}>
                        创建项目
                      </Button>
                    </p>
                  </Card>
                )}

                <div className="space-y-4">
                  <div>
                    <Label className="mb-3 block text-base">选择生成风格</Label>
                    <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
                      {styles.map((style) => (
                        <Card
                          key={style.id}
                          className={`cursor-pointer p-4 transition-all hover:border-primary ${
                            selectedStyle === style.id ? "border-primary bg-primary/5" : ""
                          }`}
                          onClick={() => setSelectedStyle(style.id)}
                        >
                          <div className="mb-2 flex items-center gap-2">
                            <div className="h-2 w-2 rounded-full bg-primary" />
                            <h3 className="font-semibold">{style.name}</h3>
                          </div>
                          <p className="text-sm text-muted-foreground">{style.description}</p>
                        </Card>
                      ))}
                    </div>
                  </div>

                  <div>
                    <Label htmlFor="prompt" className="mb-2 block text-base">
                      内容提示
                    </Label>

                    <div className="mb-3 flex flex-wrap gap-2">
                      {promptExamples.map((example, index) => (
                        <Button
                          key={index}
                          variant="outline"
                          size="sm"
                          className="h-auto py-1.5 text-xs bg-transparent"
                          onClick={() => {
                            setPrompt(example.prompt)
                            const matchingStyle = styles.find((s) => s.name === example.styleId)
                            if (matchingStyle) {
                              setSelectedStyle(matchingStyle.id)
                            }
                          }}
                        >
                          {example.title}
                        </Button>
                      ))}
                    </div>

                    <Textarea
                      id="prompt"
                      placeholder="例如：分享一家性价比超高的日料店，环境优雅，适合约会..."
                      className="min-h-32"
                      value={prompt}
                      onChange={(e) => setPrompt(e.target.value)}
                    />
                  </div>

                  <Button
                    size="lg"
                    className="w-full"
                    onClick={handleGenerate}
                    disabled={!selectedStyle || !prompt || isGenerating || (!user && trialCount >= TRIAL_LIMIT)}
                  >
                    {isGenerating ? (
                      <>
                        <Loader2 className="mr-2 h-5 w-5 animate-spin" />
                        AI 生成中...
                      </>
                    ) : (
                      <>
                        <Sparkles className="mr-2 h-5 w-5" />
                        开始生成
                      </>
                    )}
                  </Button>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* 创建任务对话框 */}
      {showCreateDialog && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-md mx-4">
            <h3 className="text-lg font-semibold mb-4">创建新任务</h3>
            <div className="space-y-4">
              <div>
                <Label htmlFor="task-title">任务标题</Label>
                <input
                  id="task-title"
                  type="text"
                  value={newTaskTitle}
                  onChange={(e) => setNewTaskTitle(e.target.value)}
                  placeholder="请输入任务标题"
                  className="w-full mt-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  autoFocus
                />
              </div>
              <div className="flex gap-2 justify-end">
                <Button
                  variant="outline"
                  onClick={() => {
                    setShowCreateDialog(false)
                    setNewTaskTitle("")
                  }}
                >
                  取消
                </Button>
                <Button
                  onClick={handleCreateTask}
                  disabled={!newTaskTitle.trim()}
                >
                  创建
                </Button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 删除任务确认对话框 */}
      {showDeleteDialog && taskToDelete && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-md mx-4">
            <h3 className="text-lg font-semibold mb-4">确认删除</h3>
            <div className="space-y-4">
              <p className="text-gray-600">
                确定要删除任务 <span className="font-medium">"{taskToDelete.title}"</span> 吗？
              </p>
              <p className="text-sm text-red-600">
                此操作不可撤销，任务及其相关历史记录将被永久删除。
              </p>
              <div className="flex gap-2 justify-end">
                <Button
                  variant="outline"
                  onClick={() => {
                    setShowDeleteDialog(false)
                    setTaskToDelete(null)
                  }}
                >
                  取消
                </Button>
                <Button
                  variant="destructive"
                  onClick={handleDeleteTask}
                >
                  确认删除
                </Button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 删除历史确认对话框 */}
      {showDeleteHistoryDialog && historyToDelete && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-md mx-4">
            <h3 className="text-lg font-semibold mb-4">确认删除历史</h3>
            <div className="space-y-4">
              <p className="text-gray-600">
                确定要删除这条历史记录
                {historyToDelete.title ? (
                  <>
                    ：<span className="font-medium">"{historyToDelete.title}"</span>
                  </>
                ) : null}
                吗？
              </p>
              <p className="text-sm text-red-600">此操作不可撤销，该历史记录将被永久删除。</p>
              <div className="flex gap-2 justify-end">
                <Button
                  variant="outline"
                  onClick={() => {
                    setShowDeleteHistoryDialog(false)
                    setHistoryToDelete(null)
                  }}
                >
                  取消
                </Button>
                <Button
                  variant="destructive"
                  onClick={handleDeleteHistory}
                >
                  确认删除
                </Button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
